package logcore

import (
	"io"
)

//Handler writes logs to somewhere
type Handler interface {
	Write(p []byte) (n int, err error)
	Close() error
}

//StreamHandler writes logs to a specified io Writer, maybe stdout, stderr, etc...
type StreamHandler struct {
	out WriteSyncer
}

func NewStreamHandler(w io.Writer) (*StreamHandler, error) {
	h := new(StreamHandler)
	h.w = w
	return h, nil
}

type ioHandle struct {
	//LevelEnabler
	fmt Format
	out WriteSyncer
}

func (c *ioHandle) Write(ent *Entry, fields []Field) error {
	buf, err := c.fmt.Formatter(ent)
	if err != nil {
		return err
	}
	_, err = c.out.Write(buf.Bytes())
	buf.Free()
	if err != nil {
		return err
	}
	if ent.Level > ErrorLevel {
		// Since we may be crashing the program, sync the output. Ignore Sync
		// errors, pending a clean solution to issue #370.
		c.Sync()
	}
	return nil
}

func (c *ioHandle) Sync() error {
	return c.out.Sync()
}

//func (c *ioHandle) clone() *ioHandle {
//	return &ioHandle{
//		LevelEnabler: c.LevelEnabler,
//		enc:          c.enc.Clone(),
//		out:          c.out,
//	}
//}
